<template>
  <div>
    <!-- 需求计划提报(N+1) -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhPlanReportN1"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="text" style="font-size:14px; font-weight:bold;margin-right:20px;">
            <span v-text="`本月：${showData.currMonth}`"></span>
            <span v-text="`提交状态: ${showData.checkStatus ? '已提交' : '未提交'}`"></span>
            <span v-text="`本月截止提报时间: ${showData.beginDate}至${showData.endDate}`"></span>
          </el-button>
          <el-button size="small" type="primary" :disabled="isDisabled" @click="addHandle(1)">新增</el-button>
          <multiuse-button size="small" type="primary" :disabled="isDisabled" :click="oneKeySubmit">一键提交</multiuse-button>
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <Drawer :visible.sync="isAdd" :title="'新增'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <addModel :rowData="formData" @close="emitcloseHandler" />
    </Drawer>
    <BaseDialog :visible.sync="isEmit" :title="'编辑'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <emitModel :rowData="formData" @close="emitcloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import { queryList, getDeadlineTime, getStatus, delByIds, submit, exportExcel ,exporturl} from '@/api/dealerSale/salesPlan/PlanReportN1';
import addModel from './addModel';
import emitModel from './emitModel';

export default {
  name: 'PlanReportN1',
  mixins: [dictionary],

  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: { isDealer: 10041001 },
      formData: {},
      showData: {
        currMonth: moment().format('YYYY年MM月'),
        checkStatus: false,
        beginDate: '',
        endDate: ''
      },
      exportLoading: false,
      isDisabled: false,
      isAdd: false,
      isEmit: false
    };
  },
  components: {
    addModel,
    emitModel
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      const res = await getStatus();
      const res1 = await getDeadlineTime();

      if (res.resultCode == 200) {
        this.showData.checkStatus = res.data;
      }
      if (res1.resultCode == 200) {
        this.showData.beginDate = res1.data.beginDate;
        this.showData.endDate = res1.data.endDate;
      }
      this.isDisabled = res1.data.endDate < moment().format('YYYY-MM-DD') || res.data ? true : false;
    },
    addHandle(type) {
      if (type == 1) {
        this.isAdd = true;
        this.formData = this.showData;
      } else {
      }
    },
    changeHandle(params) {
      this.init();
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    editHandle(row) {
      this.isEmit = true;
      this.formData = row;
    },
    emitcloseHandler(val, type) {
      this.isAdd = val;
      this.isEmit = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async oneKeySubmit() {
      await this.$confirm('请确认是否提交，提交后不能操作页面数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await submit();
          if (res.resultCode == 200) {
            this.isDisabled = true;
            this.$notify.success({ title: '提示信息', message: '提交成功' });
            this.fetchParams = Object.assign({}, this.fetchParams);
            this.init();

            return;
          }
          this.isDisabled = false;
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消提交'
          });
        });
    },
    async delHandle(row) {
      await this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delByIds([row.id]);
          if (res.resultCode == 200) {
            this.$notify.success({ title: '提示信息', message: '删除成功' });

            this.fetchParams = { ...this.fetchParams };
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 导出
    async exportHandle() {



let json = Object.assign({}, { CODE: 'CODE_0000026' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }



      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;

      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '需求计划提报（N+1）');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '产品代码',
          fieldName: 'productCode',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '产品名称',
          fieldName: 'productName',
          placeholder: '请输入'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" disabled={this.isDisabled} onClick={() => this.editHandle(props.row)}>
                  编辑
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" disabled={this.isDisabled} onClick={() => this.delHandle(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '产品代码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '品牌名称',
          dataIndex: 'brandName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系名称',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置名称',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装名称',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimColorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: `${moment()
            .subtract(-1, 'months')
            .format('YYYY年MM月')}(N+1)`,
          dataIndex: 'n1',
          filterType: 'input',
          align: 'center',
          children: [
            {
              title: '提报数量',
              dataIndex: 'quantity',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true
            }
          ]
        }
      ];
    }
  }
};
</script>
